package cn.edu.fzu.homemaking.helper;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

import cn.edu.fzu.homemaking.config.CommonConfig;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component("emailHelper")
public class EmailHelper {

    private static final Logger log    = LoggerFactory.getLogger(EmailHelper.class);

    private static final String FZU    = "福州大学";

    private static final String SYSTEM = "--家政系统";

    private static final String UTF8   = "UTF-8";

    @Resource
    private JavaMailSender      mailSender;

    @Resource
    private RabbitTemplate      rabbitTemplate;

    /** 单发邮件 **/
    public void sendMail(String email, String title, String content) {
        EmailMessage message = new EmailMessage();
        message.email = email;
        message.title = title;
        message.content = content;
        rabbitTemplate.convertAndSend(CommonConfig.EXCHANGE_TOPICS_EMAIL, "email", message);
    }


    @RabbitListener(queues = { CommonConfig.QUEUE_EMAIL })
    public void receive(EmailMessage message) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, UTF8);
            messageHelper.setFrom(FZU);
            messageHelper.setSubject(message.title + SYSTEM);
            messageHelper.setTo(message.email);
            messageHelper.setText(message.content, true);// html: true
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            log.error("send email fail | email:{},title:{}", message.email, message.title, e);
        }
    }

    @Data
    public static class EmailMessage implements Serializable {
        private String email;
        private String title;
        private String content;

    }

}
